package 多线程09_原子访问;

/**
 * @ClassName: TestThreadSyn01
 * @Author: AllenSun
 * @Date: 2022/3/18 下午10:11
 */
public class TestThreadAtomHero {


    public static void main(String[] args) {
        final HeroAtom gareen = new HeroAtom("盖伦",10000,10000);

        //创建数组存放线程对象
        int n=10000;
        Thread[] addThreads = new Thread[n];
        Thread[] reduceThreads = new Thread[n];

        for (int i=0;i<n;i++) {
            Thread t = new Thread() {
                public void run() {
                    //lock对象是final修饰的，每次执行方法之前先占有lock对象，如果占有失败就不执行
                    gareen.recover_notify();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
            addThreads[i] = t;
        }
        for (int i=0;i<n;i++) {
            Thread t = new Thread() {
                public void run() {
                    //lock对象是final修饰的，每次执行方法之前先占有lock对象，如果占有失败就不执行
                    gareen.hurt_wait();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
            reduceThreads[i] = t;
        }
        //之所以把线程对象存到数组中，就是为了每个线程都加上join，这样保证主线程在每个线程执行结束后才结束
        for (Thread t : addThreads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        for (Thread t : reduceThreads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.printf("%d个增加线程和%d个减少线程结束后%n盖伦的血量是 %.0f%n", n,n,gareen.hp);
    }



}
